< previous page page_309 next page >

Page 309
Boolean Comparisons
A long time ago (toward the beginning of this tutorial), I mentioned that it is crucial to understand why Visual Basic Boolean variables always have the value 1.
To see why this is the case, let's go back to the sample code shown on page 11 for detecting if a window has a border.
' Get the class info
    style& = GetWindowLong&(useHwnd&, GWL_STYLE)

If style& And WS_BORDER Then
    ' This code will execute if the window has a border
End If
This code will work because, if the window has a border, the expression "style& And WS_BORDER" will result in the value &H800000. This value is non-zero, so the conditional statement will work.
What would happen if you wrote your code to determine if the window did not have a border?
If Not (style& And WS_BORDER) Then
    ' This code should execute if the window does not have a border
End If
If the window does not have a border, the expression "Not (style& And WS_BORDER)" will result in "Not 0", which results in 1, or True. So the conditional statement will execute.
If the window does have a border, the expression will result in "Not &H800000", which is equal to &H7FFFFF, which is also non-zero and thus True. So the conditional statement will execute.
The condition code will always execute in this case. Clearly, this is a bug. And it's one that can be very hard to discover.
That's why Visual Basic Boolean variables always use 1 for True and 0 for False. If they didn't, conditional expressions would fail.
Why is this important for API programmers? Because whereas Visual Basic consistently uses 1 for True, the Win32 API uses any non-zero value, especially the number 1, to indicate a True result.
The best way to deal with this situation is to always compare results of API functions or bit operations with zero before doing the comparison. The example shown above can be dealt with easily using the following code:
If Not ((style& And WS_BORDER)<>0) Then
    ' This code will execute if the window does not have a border

 
< previous page page_309 next page >